<?php

namespace App\Http\Controllers;

use App\Commission;
use App\CommissionDetail;
use App\DistributionLeader;
use App\DistributionRule;
use App\DistributionTeam;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Orders;
use App\User;
use App\UserInfo;
use Illuminate\Http\Request;
use DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class DistributionController extends Controller
{
    //Admin Used
    /**
     * 设置分销规则API
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDistributionRule(Request $request){
        $highestLevel             = !is_null($request->get('highest_level')) ? $request->get('highest_level') : 1;
        $firstRatio               = !is_null($request->get('first_ratio')) ? $request->get('first_ratio') : 0;
        $secondaryRatio           = !is_null($request->get('secondary_ratio')) ? $request->get('secondary_ratio') : 0;
        $threeRatio               = !is_null($request->get('three_ratio')) ? $request->get('three_ratio') : 0;
        $minimal_withdraw_limit   = !is_null($request->get('minimal_withdraw_limit')) ? $request->get('minimal_withdraw_limit') : 0;

        $newDistributionRule = DistributionRule::first();
        if(!$newDistributionRule)
            $newDistributionRule = new DistributionRule();

        $newDistributionRule->highest_level            = $highestLevel  ? $highestLevel : 0;
        $newDistributionRule->first_ratio              = $firstRatio ? $firstRatio :0;
        $newDistributionRule->secondary_ratio          = $secondaryRatio ? $secondaryRatio : 0;
        $newDistributionRule->three_ratio              = $threeRatio ? $threeRatio : 0;
        $newDistributionRule->minimal_withdraw_limit   = $minimal_withdraw_limit ? $minimal_withdraw_limit : 0;
        $newDistributionRule->save();
        return response()->json(['level' => 'success','message' => '设置成功','data' => $newDistributionRule]);
    }

    /**
     * 设置分销规则页面
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDistributionRulePage(Request $request){

        $newDistributionRule = DistributionRule::first();
        return view('admin.distribution-set',['distribution'=>$newDistributionRule]);
    }

    /**
     * 查看用户佣金
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getUserRebate(Request $request){
        $data=Commission::orderBy('available_money','desc')->paginate(30);
        if (count($data) > 0){
            /** @var Commission $item */
            foreach ($data as $item){
                $temp_user      =User::whereId($item->user_id)->first();
                $temp_user_info =UserInfo::whereUserId($item->user_id)->first();
                $item->phone    =$temp_user         ? $temp_user->phone : '无';
                $item->nickname =$temp_user_info    ? $temp_user_info->nickname : '无';
                $item->img_url  =$temp_user_info    ? FileManager::getImgUrl($temp_user_info->photo_id) : '';
                $item->reg_time =$temp_user         ? $temp_user->created_at : '无';
            }
        }
        return view('admin.distribution-money-list',['data'=>$data]);
    }

    /**
     * 查看团长
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getDistributionLeader(Request $request){
        $data=DistributionLeader::orderBy('id','desc')->paginate(30);
        if (count($data) > 0){
            /** @var DistributionLeader $item */
            foreach ($data as $item){
                $is_reg_user    =User::whereId($item->phone)->first();
                $temp_user_info =UserInfo::whereUserId($item->user_id)->first();
                if ($is_reg_user && $item->user_id == 0) {
                    $item->user_id = $is_reg_user->id;
                    $item->save();
                }
                if ($is_reg_user)
                    $commission=CommissionDetail::whereUserId($is_reg_user->id)->first();
                else
                    $commission=false;
                $item->nickname = $temp_user_info   ? $temp_user_info->nickname : '未注册';
                $item->reg_time = $is_reg_user      ? $is_reg_user->created_at : '未注册';
                $item->img_url  = $temp_user_info   ? FileManager::getImgUrl($temp_user_info->photo_id) : '';
                $item->first_level_number = DistributionTeam::whereUserId($item->user_id)->count();
                $item->amount   = $commission ? $commission->amount : 0;
            }
        }
        return view('admin.distribution-leader-list',['data'=>$data]);
    }

    public function addDistributionLeader(Request $request){

        $id=$request->get('id');
        $phone  =$request->get('phone');
        if(!preg_match("/^(1[3456789])[0-9]{9}$/", $phone))
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);
        $record =DistributionLeader::whereId($id)->first();
        if (!$record){
            $record=new DistributionLeader();
        } else {
            $thisUser=User::wherePhone($phone)->first();
            if ($thisUser){
                if ($record->user_id==0){
                    $record->user_id=$thisUser->id;
                }
            }
        }
        $record->phone=$phone;
        $record->save();
        return response()->json(['level'=>'success','message'=>'操作成功']);

    }
    public function delDistributionLeader(Request $request){

        $id=$request->get('id');
        $record =DistributionLeader::whereId($id)->first();
        if (!$record)
            return response()->json(['level'=>'error','message'=>'该记录不存在']);
        $record->delete();
        return response()->json(['level'=>'success','message'=>'删除成功']);
    }
    /**
     * 获取分销规则API
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDistributionRule(Request $request){
        $newDistributionRule = DistributionRule::first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $newDistributionRule]);
    }

    /**
     * 新增兑换记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function exchangeRebate(Request $request){

        $user_id=$request->get('user_id');
        $amount =$request->get('amount');
        if (!is_numeric($amount))
            return response()->json(['level'=>'error','message'=>'请输入数字']);
        if (!$amount)
            return response()->json(['level'=>'error','message'=>'请输入金额']);
        $user_info=User::whereId($user_id)->first();
        if (!$user_info)
            return response()->json(['level'=>'error','message'=>'该用户不存在']);

        $commission=Commission::whereUserId($user_id)->first();
        if (!$commission)
            return response()->json(['level'=>'error','message'=>'该用户目前没有佣金']);
        if (round($amount,2) > $commission->available_money)
            return response()->json(['level'=>'error','message'=>'兑换的金额大于可用金额']);
        $rule=DistributionRule::first();
        if (!$rule)
            return response()->json(['level'=>'error','message'=>'请先设置规则']);

        if ($rule->minimal_withdraw_limit > round($amount,2))
            return response()->json(['level'=>'error','message'=>'提现金额小于最小金额']);

        DB::beginTransaction();
        try {
            $commission->available_money = $commission->available_money - round($amount,2);
            $commission->save();
            $record =new CommissionDetail();
            $record->user_id =$user_id;
            $record->type         =2;
            $record->status       =1;
            $record->amount       =round($amount,2);
            $record->remark       ='提现';
            $record->save();
        } catch (\Exception $exception){
            DB::rollback();
            return response()->json(['level'=>'error','message'=>'兑换发生错误']);
        }
        DB::commit();
        return response()->json(['level'=>'success','message'=>'兑换成功']);
    }

    //User Used
    /**
     * 获取我的佣金记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMyRebateRecord(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $page_info  =[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page_info['total']=CommissionDetail::whereUserId($user->id)->count();
        $CommissionDetail=CommissionDetail::whereUserId($user->id)->offset(($page-1)*$limit)->limit($limit)->get();
        if (count($CommissionDetail) > 0){
            /** @var CommissionDetail $item */
            foreach ($CommissionDetail as $item){
                $item->status_name=$item->status==1 ? '已结算' : $item->status==2 ? '取消结算' : '待结算';
            }
        }
        return response()->json(['level' => 'success','message' => '获取成功','data' => $CommissionDetail,'page_info'=>$page_info]);
    }

    /**
     * 查询我的佣金
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMyRebate(Request $request)
    {
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);
        $commission = Commission::whereUserId($user->id)->first();
        if (!$commission)
            return response()->json(['level' => 'success', 'message' => '你还没有佣金哦', 'data' =>[]]);
        $data=[
            'sum_amount'=>CommissionDetail::whereUserId($user->id)->whereType(1)->whereIn('status',[0,1])->sum('amount'),
            'sum_orders'=>DB::select('select count(distinct order_num) from commission_detail where type = 1 and (status =1 or status=0) and deleted_at is null and user_id = ?',[$user->id]),
            'available_money'=>$commission->available_money,
        ];
        return response()->json(['level' => 'success', 'message' => '获取成功', 'data' => $data]);
    }

    //status function,
    //system Used

    //记录邀请链
    public static function joinMyTeam($user_id,$next_user_id){
        $rule=DistributionRule::first();
        if (!$rule)
            return 0;

        $user_info=UserInfo::whereUserId($user_id)->first();
        if (!$user_info)
            return 0;
        $join_user_info=UserInfo::whereUserId($next_user_id)->first();
        if (!$join_user_info)
            return 0;

        //加入团队
        $is_in_my_team=DistributionTeam::whereUserId($user_id)->whereNextUserId($next_user_id)->first();
        if ($is_in_my_team)
            return 1;

        $is_join=DistributionTeam::whereNextUserId($next_user_id)->count();
        if ($is_join >0)
            return 1;

        $join_my_team=new DistributionTeam();
        $join_my_team->user_id     =$user_id;
        $join_my_team->next_user_id=$next_user_id;
        $join_my_team->save();
        return 1;
    }

    //支付记录返成
    public static function addRebateRecord($buyer_user_id,$order_num){
        $rule=DistributionRule::first();
        if (!$rule)
            return 0;
        $order=Orders::whereOrderNum($order_num)->first();
        if (!$order)
            return 0;
        //A->  B->C->D
        $user_id=$buyer_user_id;
        if ($rule->highest_level >=1){
            //D->C,D===user_id
            $C=DistributionTeam::whereNextUserId($user_id)->first();
            if ($C){
                if (!self::isDistributionLeader($C->user_id))
                    return 0;
                $money_L12               =new CommissionDetail();
                $money_L12->user_id      =$C->user_id;
                $money_L12->from_user_id =$user_id;
                $money_L12->order_num    =$order->order_num;
                $money_L12->level        =1;
                $money_L12->type         =1;
                $money_L12->status       =0;
                $money_L12->amount       =round($order->s_amount * $rule->first_ratio/100,2);
                $money_L12->save();
//                $user_money=Commission::whereUserId($C->user_id)->first();
//                if (!$user_money)
//                    $user_money=new Commission();
//                $user_money->available_money = $user_money->available_money + $money_L12->amount;
//                $user_money->user_id=$C->user_id;
//                $user_money->save();

                if ($rule->highest_level >=2){
                    // C->B
                    $B=DistributionTeam::whereNextUserId($C->user_id)->first();
                    if ($B){
                        $money_L23               =new CommissionDetail();
                        $money_L23->user_id      =$B->user_id;
                        $money_L23->from_user_id =$C->user_id;
                        $money_L23->order_num    =$order->order_num;
                        $money_L23->level        =2;
                        $money_L23->type         =1;
                        $money_L23->status       =0;
                        $money_L23->amount       = round($order->s_amount * $rule->secondary_ratio/100,2);
                        $money_L23->save();
//                        $user_money=Commission::whereUserId($B->user_id)->first();
//                        if (!$user_money)
//                            $user_money=new Commission();
//                        $user_money->available_money=$user_money->available_money + $money_L23->amount;
//                        $user_money->user_id=$B->user_id;
//                        $user_money->save();
//                        return 1;

                        if ($rule->highest_level >=3){
                            // B->A
                            $A=DistributionTeam::whereNextUserId($B->user_id)->first();
                            if ($A){
                                $money_L34               =new CommissionDetail();
                                $money_L34->user_id      =$A->user_id;
                                $money_L34->from_user_id =$B->user_id;
                                $money_L34->order_num    =$order->order_num;
                                $money_L34->level        =3;
                                $money_L34->type         =1;
                                $money_L34->status       =0;
                                $money_L34->amount       =round($order->s_amount * $rule->three_ratio/100,2);
                                $money_L34->save();
//                                $user_money = Commission::whereUserId($A->user_id)->first();
//                                if (!$user_money)
//                                    $user_money=new Commission();
//                                $user_money->money = $user_money->available_money + $money_L34->amount;
//                                $user_money->user_id=$A->user_id;
//                                $user_money->save();

                            }
                        }
                    }
                }
            }

        }
        return 1;
    }

    /**
     * 判断用户是否是团长
     * @param $user_id
     * @return int
     */
    public static function isDistributionLeader($user_id){
        if ($user_id==0)
            return 0;
        $exist=DistributionLeader::whereUserId($user_id)->first();
        return $exist ? 1 : 0;
    }

    /**
     * 确认返成
     * @param $order_num
     * @return int
     */
    public static function confirmRebateRecord($order_num){
        $order=Orders::whereOrderNum($order_num)->first();
        if (!$order)
            return 0;

        $rule=DistributionRule::first();
        if (!$rule)
            return 0;

        if (in_array($order->status,[4,5])){
            $details=CommissionDetail::whereOrderNum($order_num)->whereStatus(0)->whereType(1)->get();
            if (count($details) > 0){
                /** @var CommissionDetail $detail */
                foreach ($details as $detail){
                    $detail->status=1;
                    $detail->save();
                    $user_money=Commission::whereUserId($detail->user_id)->first();
                    if (!$user_money)
                        $user_money=new Commission();
                    $user_money->available_money = $user_money->available_money + $detail->amount;
                    $user_money->user_id=$detail->user_id;
                    $user_money->save();
                }
            }
            return 1;
        }
        return 0;
    }

    /**
     * 取消返成
     * @param $order_num
     * @return int
     */
    public static function cancelRebateRecord($order_num){
        $order=Orders::whereOrderNum($order_num)->first();
        if (!$order)
            return 0;

        $rule=DistributionRule::first();
        if (!$rule)
            return 0;

        $details=CommissionDetail::whereOrderNum($order_num)->whereStatus(0)->whereType(1)->get();
        if (count($details) > 0){
            /** @var CommissionDetail $detail */
            foreach ($details as $detail){
                $detail->status=2;
                $detail->save();
            }
        }
        return 1;
    }
}
